package com.example.jiaoan;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Connection;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaseActivity extends AppCompatActivity {

    public static final int ERROR_STATE = 10000; // 网络请求失败状态码
    public static final int SUCCESS_STATE = 20000;
    public static final int FAIL_STATE = 30000;
    private static final int CODE_SUCC = 200;
    private static final int STATUS_SUCC = 200;

    private Context context;


    public void setContext(Context context) {
        this.context = context;
    }

    public Context getContext() {
        return context;
    }

    /**
     * 获取基础配置【logo、系统名称】
     * @param mHandler
     */
    public void getConfig(Handler mHandler){
        commonRequest("https://teach.vshare.site/adminapi/index/base_config",mHandler,false,null,false,"");
    }

    /**
     * 通用数据请求
     * @param url 请求地址
     * @param mHandler 回调方法
     * @param isHeader 是否有额外请求头
     * @param headerList 额外请求头
     * @param isPost 是否POST请求
     * @param jsonStr POST请求数据
     */
    public void commonRequest(String url,Handler mHandler, Boolean isHeader, Map<String,String> headerList, Boolean isPost, String jsonStr){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (isHeader){
            for (String key : headerList.keySet()){
                builder.addHeader(key,headerList.get(key));
            }
        }
        if (isPost){
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),jsonStr);
            builder.post(requestBody);
        }
        Request request = builder.build();
        Message msg = new Message();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessage(ERROR_STATE);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Toast.makeText(getContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                    msg.what = FAIL_STATE;
                    if (jsonObject.getInt("code") == CODE_SUCC && jsonObject.getInt("_status") == STATUS_SUCC){
                        msg.what = SUCCESS_STATE;
                        msg.obj = jsonObject.getJSONObject("result");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mHandler.sendMessage(msg);
            }
        });
    }

    /**
     * 存储登录信息
     * @param token 登录凭证
     * @param headImg 头像
     * @param userName 用户名
     */
    public void saveLoginData(String token,String headImg,String userName){
        SharedPreferences sharedPreferences = getSharedPreferences("loginData",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("token",token);
        editor.putString("headImg",headImg);
        editor.putString("userName",userName);
        editor.apply();
    }

    /**
     * 获取登录信息
     * @param key
     * @return
     */
    public String getLoginValue(String key){
        SharedPreferences sharedPreferences = getSharedPreferences("loginData",MODE_PRIVATE);
        return sharedPreferences.getString(key,"");
    }

    /**
     * 页面跳转
     * @param curr 上下文
     * @param cls 目标页
     * @param isResult 是否需要返回
     * @param ReqCode 请求代码
     * @return 无意义
     */
    public Boolean toView(Context curr,Class<?> cls,Boolean isResult,int ReqCode){
        Intent intent = new Intent();
        intent.setClass(curr,cls);
        if (!isResult){
            startActivity(intent);
            return false;
        }
        startActivityForResult(intent,ReqCode);
        return true;
    }

    @SuppressLint("StaticFieldLeak")
    public void setWebImage(String webSrc, ImageView imageBox){
        AsyncTask<Void, Void, Bitmap> execute = new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... voids) {
                try {
                    URL url = new URL(webSrc);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    connection.connect();
                    InputStream inputStream = connection.getInputStream();
                    return BitmapFactory.decodeStream(inputStream);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                if (bitmap != null) {
                    imageBox.setImageBitmap(bitmap);
                } else {
                    imageBox.setImageResource(R.drawable.ic_launcher_background);
                }
            }
        }.execute();
    }

}
